import moment from 'moment';
import _ from 'lodash';

import getElapsed from '@util/get-elapsed';

const computeTimeConsumed = record => {
  if (_.isEmpty(record)) {
    return '-';
  }
  const { lastStart, lastEnd, maxDetectionTaskParams, lastPaused, systemTime } = record;

  // 计算定时任务的执行时间
  const timing = _.get(maxDetectionTaskParams, 'timing', {});
  const { dailyStart, dailyEnd, startAt } = timing;

  if (!dailyStart || !dailyEnd) {
    // 当周期结束时间还停留在上轮时
    if (lastEnd && lastStart && lastEnd < lastStart) {
      return getElapsed(lastStart, systemTime);
    }
    return lastStart && lastEnd ? getElapsed(lastStart, lastEnd) : '-';
  }

  const endTimeMoment = moment(dailyEnd, 'HH:mm');
  const startTimeMoment = moment(dailyStart, 'HH:mm');
  const cycleTime = endTimeMoment.add(Number(dailyStart > dailyEnd), 'day') - startTimeMoment;

  const taskStop = lastEnd || lastPaused || '';
  const runningDay = moment(taskStop) - moment(startAt, 'YYYY-MM-DD');
  let runningRound = moment.duration(runningDay).days() + 1;

  const endMinute = moment(taskStop).format('HH:mm');
  let tmpTime = 0;

  // 未跨零点的任务
  if (dailyStart < dailyEnd) {
    if (endMinute < dailyStart) {
      // 未开始
      runningRound--;
    } else if (endMinute < dailyEnd) {
      //没有扫描完
      runningRound--;
      tmpTime = endTimeMoment - moment(endMinute, 'HH:mm');
    }
  } else {
    // 跨零点的任务 23:30-00:30
    runningRound--;
    if (endMinute < dailyEnd) {
      // 00:20
      runningRound--;
      tmpTime = moment(endMinute, 'HH:mm').add(1, 'day') - startTimeMoment;
    }
    if (endMinute > dailyStart) {
      // 23:50
      tmpTime = moment(endMinute, 'HH:mm') - startTimeMoment;
    }
  }
  const taskStopArr = taskStop.split(':');
  const costSecond = (taskStopArr[taskStopArr.length - 1] || 0) * 1000;
  const costTime = runningRound * cycleTime + tmpTime + costSecond;
  return getElapsed(moment(), moment() + costTime);
};

export default computeTimeConsumed;
